(function(window,undefined){
	/*개발자 이름, 파일명*/
	var Minhyung = {};	
	window.Minhyung = window.Minhyung || Minhyung;
	
	var customerCare = Minhyung.customerCare = {}; /*고객관리*/
	var storeCare = Minhyung.storeCare = {}; /*상점관리*/ 
	
	
/*상점관리 페이지*/                                     
	storeCare.stores = {};
	
	storeCare.mainViewBlock = function(){
		var _store_id = getUrlId();
		var _user_id = sessionStorage.getItem('user_id');
		var _landmark = sessionStorage.getItem('landmark_code');
		$.ajax({
			type:"post",
			url:ajaxURL+"store.php?action=loadMainInfo",
			data:{user_id:_user_id,store_id:_store_id,landmark:_landmark},
			dataType:"json",
			success:function(result){
				console.log('seller_mainViewBlock');
				console.log(result);
				storeMap(result.latitude, result.longitude, result.name);
				load_map(result.latitude, result.longitude);
				
				if(result.addr0 == null){
					result.addr0 = '';
				}
				if(result.addr1 == null){
					result.addr1 = '';
				}
				if(result.addr2 == null){
					result.addr2 = '';
				}
				if(result.addr3 == null){
					result.addr3 = '';
				}
				if(result.addr4 == null){
					result.addr4 = '';
				}
				
				if(result.isCoupon==true){
					result.isCoupon = '<img src="images/icon_coupon.png" alt="쿠폰">';
				} else{
					result.isCoupon = '';
				}
				
				if(!result.store_image==null || result.store_image==""){
					result.store_image = 'images/default_store.png';
				}
				
				result.address = result.addr0 + ' ' + result.addr1 + ' ' + result.addr2 + ' ' + result.addr3 + ' ' + result.addr4;
				storeCare.stores = result;
				
				store_template.mainViewBlock(result);
				Store.loadFavoriteUser(result.storeFavoriteUser,0,result.isFavorite);
				Store.store_listener();
				storeCare.listener();
				
			}
		});
	};

	storeCare.listener = function(){
		$('#extraInfoEdit').off('click').on('click' ,function(){
			store_template.mainViewFixedBlock(storeCare.stores);
		});
		
		$('#detailInfoEdit').off('click').on('click' , function(){
			store_template.detailViewFixedBlock();
		});
		
		$('#galleryEdit').off('click').on('click' , function(){
			$('#storeGallery,.modalBg').show();
		});
		
		$('#galleryClose').off('click').on('click' , function(){
			$('#storeGallery,.modalBg').hide();
		});

		
		$('#extraInfo_fixed_commit').off('cilck').on('click' , function(){
			storeCare.mainViewBlock();
		});
		
		$('#detailInfo_fixed_commit').off('click').on('click' , function(){
			Store.detailViewBlock();
		});
		
	}
	
	var storeMap = function(_latitude,_longitude,_storeName){	
		$('#showMapBtn').off('click').on("click",function(event){
			event.preventDefault();
			
			$('#storeMapModal,.modalBg').show();
			bigMapBlock(_latitude, _longitude,_storeName);
		});
		
		$('#closeMapBtn').off('click').on("click",function(event){
			event.preventDefault();
			$('#storeMapModal,.modalBg').hide();
		});
	};

	var load_map = function(_lat, _lng) {
		var element = "map_canvas";
	    var map;
	    
	    var latlng = new google.maps.LatLng(_lat, _lng);
    	var myOptions = {
    		scrollwheel : false,
			zoom : 16,
			center : latlng,
			mapTypeId : google.maps.MapTypeId.ROADMAP,
			panControl : false,
			zoomControl : false,
			scaleControl : false,
			streetViewControl : false,
			overviewMapControl : false,
			mapTypeControl : false,
			zoomControlOptions : { style : google.maps.ZoomControlStyle.LARGE,
				position :
				google.maps.ControlPosition.LEFT_CENTER
			}
    	};
    
	    map = new google.maps.Map(document.getElementById(element), myOptions);
	    var markerOptions = {
	    	position:latlng,
	        map:map,
	        draggable:false,
	        icon:'images/black_icon.png'
   		};
    	var marker = new google.maps.Marker(markerOptions);
	};
	
	var compareTime = function(_weekDayStart,_weekDayEnd,_weekendStart,_weekendEnd){
		var openStatus;
		
		var _weekDayStart = _weekDayStart.split(':');
		var _weekDayEnd = _weekDayEnd.split(':');
		
		var _weekendStart = _weekendStart.split(':');
		var _weekendEnd = _weekendEnd.split(':');
		
		var _current = new Date();
		var _currentTime =new Date('1989','01','02',_current.getHours(),_current.getMinutes(),_current.getSeconds());
		if(_currentTime.getDay()==0 || _currentTime.getDay()==6){/*주말*/
			var _weekendStart = new Date('1989','01','02',_weekendStart[0],_weekendStart[1],_weekendStart[2]);
			var _weekendEnd = new Date('1989','01','02',_weekendEnd[0],_weekendEnd[1],_weekendEnd[2]);

			if((_weekendStart-_currentTime)<=0 && (_weekendEnd-_currentTime)>=0){
				openStatus='open';
			}else{
				openStatus='close';
			}
		}else{
			var _weekDayStart = new Date('1989','01','02',_weekDayStart[0],_weekDayStart[1],_weekDayStart[2]);
			var _weekDayEnd = new Date('1989','01','02',_weekDayEnd[0],_weekDayEnd[1],_weekDayEnd[2]);

			if((_weekDayStart-_currentTime)<=0 && (_weekDayEnd-_currentTime)>=0){
				openStatus='open';
			}else{
				openStatus='close';
			}
		}
		return openStatus;
		
	};	


	var store_template = {
		mainViewBlock : function(result){ 
			var info='';
			// info += '<div class="storeFlag rank"><span>12</span></div>';	     	
		    // info += '<div class="storeFlag coupon"><span>'+result.storeCouponCount+'</span></div>';
		    if(compareTime(result.weekday_start,result.weekday_end,result.weekend_start,result.weekend_end)=='open'){
		    	 info += '<div class="openClose open"></div>';
		    }else{
		    	 info += '<div class="openClose close"></div>';
		    }
		   	info += '<a href="#" class="imgEditBtn"><img src="images/btn_edit_photo.png" alt="btn_edit_photo"/></a>';
		    info += ' <div class="thumbWrap">';
		    info += '<a href="store_view.php">';
		    info += '<img src="'+result.store_image+'" width="300px" height="240px" alt="thumb_store_1">'
		    info += '</a>';     
		    info += '</div>';
		    info += '<div class="infoWrap">';
		    info += '<a class="title" href="store_view.php">'+result.name+' '+result.isCoupon+'</a>';
		    info += '<div class="tags">'+result.category_name+' <span>|</span> '+result.addr2+'</div>';
			info += '<div class="values">';
			info += '만족도 <b>' + result.satisfaction + '%</b>&nbsp;&nbsp;&nbsp;&nbsp;토크 <b>'+result.talk_count+'</b>개';
			info += '</div>';
		    info += '<a class="shareBtn">공유하기</a>';
		    info += '<div class="extraInfo">';
		    info += '<div class="editBtnWrap">';
		    info += '<a href="#" id="extraInfoEdit" class="editBtn2">수정하기</a>';
		    info += '</div>';
		    info += '<table><tr>';
		    info += '<th>전화번호</th><td>'+result.telephone+'</td></tr>';
		    info += '<tr><th>주소</th><td>'+result.address+'</td></tr>';
		    info += '<tr><th>시간</th><td>평일 '+result.weekday_start+' ~ '+result.weekday_end+'<br/>주말 '+result.weekend_start+' ~ '+result.weekend_end+'</td></tr>';
		    info += '</table>';
		    info += '</div>';
		    info += '<div data-store_id="'+result.store_id+'" id="friends" class="friends">';
            info += '</div>';  
			info += '<div class="favorites">';
		    info += '<span class="weekly"> <b>'+result.favoriteCountInWeek+'</b>명</span><br>';
            info += '<span class="total"> <b>'+result.favorite_count+'</b>명</span>';
		    info += '</div></div>';
		    info += '<div class="clear"></div>';
			
			$('.storeView > li').html(info);
		},
		
		mainViewFixedBlock : function(result){
			var info='';
			// info += '<div class="storeFlag rank"><span>12</span></div>';	     	
		    // info += '<div class="storeFlag coupon"><span>'+result.storeCouponCount+'</span></div>';
		    if(compareTime(result.weekday_start,result.weekday_end,result.weekend_start,result.weekend_end)=='open'){
		    	 info += '<div class="openClose open"></div>';
		    }else{
		    	 info += '<div class="openClose close"></div>';
		    }
		   	info += '<a href="#" class="imgEditBtn"><img src="images/btn_edit_photo.png" alt="btn_edit_photo"/></a>';
		    info += ' <div class="thumbWrap">';
		    info += '<a href="store_view.php">';
		    info += '<img src="'+result.store_image+'" width="320px" height="240px" alt="thumb_store_1">'
		    info += '</a>';     
		    info += '</div>';
		    info += '<div class="infoWrap">';
		    info += '<a class="title" href="store_view.php">'+result.name+' '+result.isCoupon+'</a>';
		    info += '<div class="tags">'+result.category_name+' <span>|</span> '+result.addr2+'</div>';
			info += '<div class="values">';
			info += '만족도 <b>' + result.satisfaction + '%</b>&nbsp;&nbsp;&nbsp;&nbsp;토크 <b>'+result.talk_count+'</b>개';
			info += '</div>';
		    info += '<a class="shareBtn">공유하기</a>';
		    info += '<div class="extraInfo">';
		    info += '<table class="fixed_extraInfo">';
		    info += '<tr><th>전화번호</th><td><select><option>010</option></select> - <input class="textInput small " style="width:60px;"/> - <input class="textInput small" style="width:60px;"/></td></tr>';
		    info += '<tr><th>주소</th><td><select><option>광역시/도</option></select> <select><option>시/군/구</option></select> <select><option>동/읍/면</option></select><div class="clear" style="height:5px;"></div>';
		    info += '<input class="textInput small " style="width:230px;"/>';
		    info += '</td></tr><tr>';
		    info += '<th>시간</th><td>평일 <input class="textInput small " style="width:60px;"/> ~ <input class="textInput small " style="width:60px;"/><div class="clear" style="height:5px;">';
		    info += '</div>주말 <input class="textInput small " style="width:60px;"/> ~ <input class="textInput small " style="width:60px;"/></td>';
		    info += '</tr>';
		    info += '</table>';
		    info += '</div>';
		    info += '<div class="buttonWrap right" style="padding-top:5px;">';
		    info += '<a href="#" id="extraInfo_fixed_commit"><img src="images/btn_edit_comp.png" alt="btn_edit_comp" /></a>';
		    info += '</div>';
		    info += '<div data-store_id="'+result.store_id+'" id="friends" class="friends">';
            info += '</div>';  
			info += '<div class="favorites">';
		    info += '<span class="weekly"> <b>'+result.favoriteCountInWeek+'</b>명</span><br>';
            info += '<span class="total"> <b>'+result.favorite_count+'</b>명</span>';
		    info += '</div></div>';
		    info += '<div class="clear"></div>';		    

			$('.storeView > li').html(info);
			storeCare.listener();
		    
		},
		detailViewFixedBlock : function(){

			var info = '';
			info += '<table>';
			info += '<tr><th  width="80">이용 정보</th><td class="useInfo">';
			info += '<input type="checkbox" /> 카드가능 &nbsp;&nbsp;&nbsp; <input type="checkbox" /> 예약가능 &nbsp;&nbsp;&nbsp;';
			info += '<input type="checkbox" /> 단체가능 &nbsp;&nbsp;&nbsp;  <input type="checkbox" /> 주차가능  &nbsp;&nbsp;&nbsp; <input type="checkbox" /> 발렛파킹 </td>';
			info += '</tr><tr><th>메뉴</th><td>';
			info += '<textarea class="textInput" style="height:120px; width:530px;"></textarea>';
			info += '</td></tr><tr><th>소개</th><td>';
			info += '<textarea class="textInput" style="height:120px; width:530px;">';
			info += '</textarea></td>';
			info += '</tr><tr><th>오시는 길</th><td>';
			info += '<textarea class="textInput" style="height:120px; width:530px;"></textarea>';
			info += '</td></tr>';
			info += '</table>';
			info += '<div class="buttonWrap right" style="padding-top:5px;">';
			info += '<a href="#" id="detailInfo_fixed_commit"><img src="images/btn_edit_comp.png" alt="btn_edit_comp" /></a>';
			info += '</div><div class="clear"></div>';
			

			$('.storeInfoWrap').html(info);
			storeCare.listener();
		}			
		
	}
	
/*고객관리 페이지*/	
	customerCare.customers = {};

	
	customerCare.customerListBlock = function(){
		
   		template.drawInit();
		loadCustomer(template.drawCustomer);
		
		$('.customer_check_all').off('click').on('click' , function(){
			if($(this).attr("checked") == "checked"){
				$('input[name=customer_list]').attr("checked" , true);
			} else {
				$('input[name=customer_list]').attr("checked" , false);
			}
		});
	}
	
	var loadCustomer = function(succssCallback){
		var _store_id = sessionStorage.getItem('owner_store_id');
		console.log(_store_id);
		
		 if(!succssCallback){
			 alert(NONE_CALLBACK);
		 }
		
		$.ajax({
			type:'post',
			url:ajaxURL + 'customer.php?action=loadCustomer',
			data:{ store_id : _store_id },
			dataType:'json',
			success:function(result){
				console.log(result);
				$('.countWrap').html('(<b>'+ result.length +'</b>명)');
				$.each(result,function(){
					if(this.is_interest == 0){
						this.is_interest = '일반고객';
					}else{
						this.is_interest = '핵심고객';
					}
					if(this.user_gender == "MAN" || this.user_gender == "male"){
						this.user_gender = "남자";
					}else{
						this.user_gender = "여자";
					}
					if(this.user_activity == false){
						this.user_activity = 0;
					}
					succssCallback(this);
				});
				customerCare.customers = result;
				
			}
		});
	};
	
	var template = {
		drawInit : function(){
			$('.friendTable').empty();
			
			var html = '';
			html += '<tr>';
			html += '<th>분류</th>';
			html += '<th>닉네임</th>';
			html += '<th>성별</th>';
			html += '<th>생일</th>';
			html += '<th>활동지수</th>';
			html += '<th>친구</th>';
			html += '<th><input class="customer_check_all" type="checkbox" checked="checked" /></th>';
			html += '</tr>'; 	
			
			$('.friendTable').append(html);		
		},
		
		drawCustomer : function(_data){
			var html = '';
			html += '<tr>';
			html += '<td>'+ _data.is_interest +'</td>';
			html += '<td><a href="#">'+ _data.user_name +'</a></td>';
			html += '<td>'+ _data.user_gender +'</td>';
			html += '<td>' + _data.user_birthday + '</td>';
			html += '<td>'+ _data.user_activity +'</td>';
			html += '<td>'+ _data.friend_count +'</td>';
			html += '<td><input type="checkbox" name="customer_list" checked="checked" /></td>';
			html += '</tr>';	
			
			
			$('.friendTable').append(html);				
			
		}

	}


	customerCare.sendMessageOptionBlock = function(){
		$('.all_age').off('click').on('click' , function(){
			if($(this).attr("checked") == "checked"){
				$('input[name=age]').attr("checked" , false);
			} 		
		});
		$('.ten,.twenties,.thirty,.forty,.fifty,.sixty').off('click').on('click' , function(){
				$('.all_age').attr("checked" , false);
		});
		
		
		
		$('#sendMessage').off('click').on('click', function(){
			var sendMessageUser = customerCare.customers;
			var d = new Date();
			var messageToUser = new Array();
			var to_users = new Array(); 

			$.each(sendMessageUser, function() {
				var _year = this.user_birthday.split("-")[0];
				var _month = this.user_birthday.split("-")[1];
				var age = ((d.getFullYear()-_year)+1)/10
				age = Math.floor(age);
				if($(':radio[name="customer"]:checked').attr('class') == "this_month_birthday"){
					if((d.getMonth()+1) != _month){
						return true;
					}
				}
				
				if($(':radio[name="gender"]:checked').attr('class') == "gender_male"){
					if(this.user_gender != "남자"){
						return true;
					}
				}else if($(':radio[name="gender"]:checked').attr('class') == "gender_female"){
					if(this.user_gender != "여자"){
						return true;
					}
				}
				
				if($('.all_age').attr('checked') != "checked"){
					switch(age){
						case 1:
							if ($('.ten').attr('checked') != "checked") { return true; }
							break;
						case 2:
							if ($('.twenties').attr('checked') != "checked") { return true; }
							break;
						case 3:
							if ($('.thirty').attr('checked') != "checked") { return true; }
							break;
						case 4:
							if ($('.forty').attr('checked') != "checked") { return true; }
							break;
						case 5:
							if ($('.fifty').attr('checked') != "checked") { return true; }
							break;
						case 6:
							if ($('.sixty').attr('checked') != "checked") { return true; }
							break;
						default:
							return true;
							break;
						}
					}
				
				console.log(this.user_name);
				messageToUser.push(this);
				to_users.push(this.user_id);
			}); 			
			if(messageToUser.length!=0){
				$('#friendMsg,.modalBg').show();
				customerCare.sendMessageBlock(messageToUser , to_users);
			}else { alert('해당하는 고객이 없습니다.'); }
		});
	};
	
	customerCare.sendMessageBlock = function(messageToUser , to_users){
		$('#cancelBtn,.modalClose').off('click').on('click' , function(){
			$('#friendMsg,.modalBg').hide();
		});
		$('#writeBtn').off('click').on('click' , function(){
			sendMessage(to_users);
		});

		$('.to_user').empty();
		var html = '';
		if(messageToUser.length>3){
			$.each(messageToUser , function(idx){
				if(idx > 3){
					return false;
				}
				html += '<b>'+ this.user_name +'</b>,';
			});
			html += '외 <b>'+ (messageToUser.length-3) +'</b>명';
		}
		else{
			$.each(messageToUser , function(idx){
				html += '<b>'+ this.user_name +'</b>,';
			});
			html = html.substring(0,html.length-2);
		}
		
		$('.to_user').append(html);
		
	}
	
	 var sendMessage = function(to_users){
		var _message = $('.textInput').val();
		var _store_id = 39467;
		var _users = to_users;
		console.log(_users);

		$.ajax({
			type:'post',
			url:ajaxURL + 'customer.php?action=sendToUserMessage',
			data:{
				 store_id : _store_id,
				 message : _message,
				 users : _users,
				 
				 },
			success:function(result){
				console.log(result);
				alert('메세지를 보냈습니다.');
				$('#friendMsg,.modalBg').hide();

			}
		});

	}

	
	
})(window);
